package com.lgj.auth.code.customize.mobile;


import com.lgj.auth.code.service.CustomerUserDetailService;
import com.lgj.exception.BusinessException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import com.lgj.message.sms.SmsUtils;

import java.util.HashSet;

/**
 * @author: guangjie.liao
 * @Date: 2022/12/4 12:06
 * @Description: 手机短信登陆认证
 */
public class SmsVerificationCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public SmsVerificationCodeAuthenticationProvider(UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String mobileNumber = (String) authentication.getPrincipal();
        String verificationCode = (String) authentication.getCredentials();

        if (!SmsUtils.verificationCodeIsOk(mobileNumber,verificationCode)){
            throw new BusinessException("认证失败，验证码不正确！");
        }
        //账号信息验证
        UserDetails userDetails = ((CustomerUserDetailService) userDetailsService).loadUserByUsername(mobileNumber);
        SmsVerificationCodeAuthenticationToken result = new SmsVerificationCodeAuthenticationToken(userDetails, authentication.getCredentials(), new HashSet<>());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsVerificationCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
